import { defHttp } from './axios';
import type { AxiosRequestConfig } from 'axios';
import type { RequestOptions } from '/#/axios';

import { autoPost } from '@/utils/http/auto';

export { autoPost };

export /**
 * 创建一个适配openapi-ts-request的请求函数
 * 这个函数支持两种调用方式:
 * 1. request(config, options) - 与defHttp.request保持一致
 * 2. request(url, config) - 支持openapi-ts-request生成的代码格式
 *
 * @param urlOrConfig URL字符串或Axios请求配置
 * @param configOrOptions 请求配置或选项
 * @returns Promise
 */
function request<T = any>(
  urlOrConfig: string | AxiosRequestConfig,
  configOrOptions?: AxiosRequestConfig & RequestOptions,
): Promise<T> {
  // 如果第一个参数是字符串(URL)，则适配openapi-ts-request格式
  if (typeof urlOrConfig === 'string') {
    const url = urlOrConfig;
    const config = configOrOptions || {};

    // 提取options选项
    const { errorMessageMode, successMessageMode, ...axiosConfig } = config;

    // 构建RequestOptions
    const options: RequestOptions = {};
    if (errorMessageMode) options.errorMessageMode = errorMessageMode;
    if (successMessageMode) options.successMessageMode = successMessageMode;

    // 构建AxiosConfig
    const requestConfig: AxiosRequestConfig = {
      url,
      ...axiosConfig,
    };

    // 调用defHttp.request
    return defHttp.request<T>(requestConfig, options);
  }

  // 如果第一个参数是对象，则按原格式传递
  return defHttp.request<T>(urlOrConfig, configOrOptions as RequestOptions);
}

// 导出其他请求方法
export function get<T = any>(
  url: string,
  config?: AxiosRequestConfig & RequestOptions,
): Promise<T> {
  return request<T>(url, { ...config, method: 'GET' });
}

export function post<T = any>(
  url: string,
  config?: AxiosRequestConfig & RequestOptions,
): Promise<T> {
  return request<T>(url, { ...config, method: 'POST' });
}

export function put<T = any>(
  url: string,
  config?: AxiosRequestConfig & RequestOptions,
): Promise<T> {
  return request<T>(url, { ...config, method: 'PUT' });
}

export function del<T = any>(
  url: string,
  config?: AxiosRequestConfig & RequestOptions,
): Promise<T> {
  return request<T>(url, { ...config, method: 'DELETE' });
}

// 默认导出
export default {
  autoPost,
  request,
  get,
  post,
  put,
  delete: del,
};
